// 判断用户是否登录
var username = getCookie('username')
if(!username){
    layer.msg('非法访问！',{
        icon: 2,
        time: 2000
    }, function(){
        location.href = '登录.html?callback='+location.href
    })
}else{
    // 发送请求获取当前用户信息
    $.ajax({
        url: 'http://localhost:8888/users/info?id='+getCookie('userId'),
        headers: {
            authorization: localStorage.getItem('token') || ''
        }
    }).then(res => {
        console.log(res);
        if(res.code === 1){
            var html = `
                <tr>
                    <td>用户名：</td>
                    <td>${res.info.username} </td>
                </tr>
                <tr>
                    <td>昵称：</td>
                    <td><input type="text" name="nickname" value="${res.info.nickname}" /></td>
                </tr>
                <tr>
                    <td>身份：</td>
                    <td>${res.info.identity} </td>
                </tr>
                <tr>
                    <td>性别：</td>
                    <td><input type="text" name="gender" value="${res.info.gender}"> </td>
                </tr>
                <tr>
                    <td>年龄：</td>
                    <td><input type="text" name="age" value="${res.info.age}"> </td>
                </tr>
                <tr>  
                    <td></td>
                    <td>
                        <input class="submit" type="button" value="提交修改">
                    </td>
                </tr>
            `
            $('.rightcontent tbody').html(html)
            // ajax成功渲染页面以后，再点击提交
            submit()
        }

    })
}

// 定义提交修改的函数
function submit(){
    $('.submit').click(function(){
        var age = $('[name="age"]').val()
        var gender = $('[name="gender"]').val()
        var nickname = $('[name="nickname"]').val()
        $.ajax({
            url: 'http://localhost:8888/users/update',
            method: 'post',
            headers: {
                authorization: localStorage.getItem('token') || ''
            },
            data: {
                id: getCookie('userId'),
                age,
                gender,
                nickname
            }
        }).then(res => {
            // console.log(res);
            if(res.code === 1){
                layer.msg(res.message, {
                    icon: 1,
                    time: 1500
                }, function(){
                    location.href = 'userinfo.html'
                })
            }
        })
    })
}